/**
 * Created by yanghaibo
 */
var activityManageParam = {
  inited: false, // 初始化页面是否完成
  params: {
    pageNo: 1,
    pageSize: 10,
    status: 0,
    type: 0
  } // 查询参数
};
(function(doc, win) {
  //加载权限信息
  var createActivityAuth = false;
  var lookActivityAuth = false;

  var BindEvent = function() {
    //绑定下拉刷新
    refreshItem({
      target: "#activityManagePage .page-body .activity-list-wrap-content",
      callBack: function(reset) {
        activityManageParam.params.pageNo = 1;
        var controller = new ActivityManageController();
        controller.getActivityList(activityManageParam.params, reset);
      }
    });

    addMoreItem({
      target: "#activityManagePage .page-body .activity-list-wrap-content",
      callBack: function(reset) {
        activityManageParam.params.pageNo++;
        var controller = new ActivityManageController();
        controller.getActivityList(activityManageParam.params, reset);
      }
    });
  };

  if ($("#activityManagePage").length) {
    BindEvent();
  }

  $(doc).on("pageAnimationStart", "#activityManagePage", function() {
    BindEvent();
  });

  // sui 页面就绪时间
  $(doc).on("pageInit", "#activityManagePage", function(
    e,
    pageId,
    $page,
    isBack
  ) {
    if (
      $("#activityManagePage .tab-wrap>li")
        .eq(0)
        .hasClass("selected")
    ) {
      commonVerifyAuthCode(function(){
        lookActivityAuth = commonHasAuthCode("app.market.activitymanage.view");
        createActivityAuth = commonHasAuthCode("app.marketingcenter.createactivity");
        initMarketingTool();
      });
    }

    //var reloadFlag = CommonUtil.takeOutParamObject().reload;
    var reloadFlag = GetQueryString("reload");//新首页（vue）通过url传过来的参数
    if (reloadFlag) {
      CommonUtil.removeParamObject();
      switchPage($("#activityManagePage .tab-wrap>li").eq(1));
      activityManageParam.params = {
        pageNo: 1,
        pageSize: 10,
        status: 0,
        type: 0
      };
      var controller = new ActivityManageController();
      controller.getActivityList(activityManageParam.params);
      return;
    }
    if (isBack) {
      // if (activityManageFilterParam.status === activityManageParam.params.status &&
      //     activityManageFilterParam.type === activityManageParam.params.type) {
      //         return; // 搜索条件没变，不需要处理
      //     } else {
      //     }
      activityManageParam.params = {
        pageNo: 1,
        pageSize: 10,
        status: activityManageFilterParam.status,
        type: activityManageFilterParam.type
      };
      var controller = new ActivityManageController();
      controller.getActivityList(activityManageParam.params);
    } else if (!activityManageParam.inited) {
      CommonUtil.hideElement("#activityManagePage .header .right a"); // 隐藏筛选项
      switchPage($("#activityManagePage .tab-wrap>li.selected"));
      activityManageParam.params = {
        pageNo: 1,
        pageSize: 10,
        status: 0,
        type: 0
      };
      var controller = new ActivityManageController();
      controller.getActivityList(activityManageParam.params);
    }
  });

  // 跳转活动详情
  $(doc).on("click", "#activityManagePage .activity-list a", function() {
    if (!lookActivityAuth) {
      return;
    }
    var campId = $(this).attr("campId");
    var outBizNo = $(this).attr("outBizNo");
    var activityStatus = $(this).attr("activityStatus");
    CommonUtil.injectParamObject({
      campId: campId,
      outBizNo: outBizNo,
      activityStatus: activityStatus
    });

    //token校验
    var serverUrl = App.serverUrl + "serviceMarket/checkAuthToken.do";
    var sucFunc = function(result) {
      common.closeLoading();
      if (String(result.success) == "true") {
        $.router.load("activity_details.html", true);
      } else {
        var toAuthorizeUrl =
          App.bmwServiceUrl + "?" + App.urlParam + "#/toAuthorize";
        AppUtil.call(AppUtil.APIS.PUSH_WINDOW, {
          url: toAuthorizeUrl,
          target: "server",
          param: {
            title: {
              title: "去授权",
              color: "#333333",
              background: "#ffffff"
            }
          }
        });
      }
    };

    var failFunc = function() {
      common.closeLoading();
      log4JS.info("getOAuthCode failed. http status not 200");
      DialogUtil.dialogWarn();
    };
    CommonUtil.sendJsonpRequest({
      url: serverUrl,
      success: sucFunc,
      error: failFunc,
      params: null,
      useDefaultLoading: true
    });
  });

  // 跳转创建活动
  $(doc).on("click", "#activityManagePage .swiper-slide a.btn", function() {
    var type = $(this).attr("type");
    CommonUtil.sendJsonpRequest({
      url: App.serverUrl + "/merchantApp/activity/activityCreateCheck.do",
      params: { activityType: type },
      success: function(result) {
        if (result && result.success) {
          if (result.resultObject.totalCount >= 500) {
            DialogUtil.dialogConfirm({
              title: "已超过限制",
              content:
                "未开始和进行中的活动数量超过限制，可终止部分活动，再来进行创建",
              btnLeft: "知道了"
            });
          } else if (type == 48 && result.resultObject.currentCount >= 1) {
            DialogUtil.dialogConfirm(
              "卡开关怀活动只能同时进行一个，当前已经有进行中的活动了"
            );
          } else if (result.resultObject.currentCount >= 1) {
            DialogUtil.dialogConfirm({
              title: "",
              content:
                "已经有 " +
                result.resultObject.currentCount +
                " 个同类型的活动，确定要继续创建新活动吗？",
              btnLeft: "取消",
              btnRight: "继续创建",
              callbackRight: function() {
                CommonUtil.injectParamObject({ activityType: type });
                if (type == 47) {
                  $.router.load("create_activity_dpyx.html", true);
                } else if (type == 35) {
                  $.router.load("create_activity_xfsq.html", true);
                } else {
                  $.router.load("create_activity_xhyzm.html", true);
                }
              }
            });
          } else {
            CommonUtil.injectParamObject({ activityType: type });
            if (type == 47) {
              $.router.load("create_activity_dpyx.html", true);
            } else if (type == 35) {
              $.router.load("create_activity_xfsq.html", true);
            } else {
              $.router.load("create_activity_xhyzm.html", true);
            }
          }
        } else if (result.code == 996) {
          //未授权，跳转至授权页
          var toAuthorizeUrl =
            App.bmwServiceUrl + "?" + App.urlParam + "#/toAuthorize";
          AppUtil.call(AppUtil.APIS.PUSH_WINDOW, {
            url: toAuthorizeUrl,
            target: "server",
            param: {
              title: {
                title: "去授权",
                color: "#333333",
                background: "#ffffff"
              }
            }
          });
        } else {
          DialogUtil.dialogWarn(result.msg);
        }
      }
    });
  });

  /**
   * 初始化营销工具
   */
  function initMarketingTool() {
    var userInfoFuture = CommonUtil.getUserServiceInfo();
    var proServiceType = 0;
    if (userInfoFuture.finish && userInfoFuture.data) {
      proServiceType = userInfoFuture.data.proServiceType;
    } else {
      var loopCount = 0;
      var intervalObj = setInterval(function() {
        if (userInfoFuture.finish) {
          if (userInfoFuture.data)
            proServiceType = userInfoFuture.data.proServiceType;
          window.clearInterval(intervalObj);
        } else if (loopCount > 10) {
          window.clearInterval(intervalObj);
        }
        loopCount++;
      }, 100);
    }
    // 营销工具种类
    var marketingTools = [
      // {
      //     name: "单品营销",
      //     type: 47,
      //     image: "icon dp",
      //     desc: "针对单款产品的营销活动，可通过扫码或活动领取，配合门店活动，可大大增加到店顾客对单款商品的消费数量。"
      // },
      {
        name: "新会员招募",
        type: 46,
        image: "icon xhy",
        desc:
          "从未在店内使用过支付宝付款的顾客可在口碑专属优惠活动页面领取，对新会员的首次到店消费有很强刺激。"
      },
      {
        name: "消费送券",
        type: 35,
        image: "icon xfs",
        desc:
          "会员消费后满足条件即可领取，优惠券直接发放到会员支付宝卡包，帮助商家大大提升回头客数量。"
      },
      {
        name: "扫码送券",
        type: 25,
        image: "icon sm",
        desc:
          "顾客通过扫码领券，可配合店内活动在线下使用，也可发布在口碑专属优惠吸引新客到店。"
      }
    ];
    if (proServiceType == 1) {
      marketingTools.push({
        name: "开卡关怀",
        type: 48,
        image: "icon kk",
        desc:
          "在活动期间，成功开通会员卡的会员，可领取一张专属优惠券作为奖励，是鼓励开通会员卡的常规手段。"
      });
    }

    var initialSlide = 0;
    if (swiper) {
      initialSlide = $(
        "#activityManagePage .swiper-container .swiper-slide"
      ).index(".swiper-slide-active");
    }
    CommonUtil.render(
      $("#activityManagePage .marketing-tool"),
      "marketingToolTpl",
      { data: marketingTools,createActivityAuth:createActivityAuth}
    );
    //滑动
    swiper = new Swiper("#activityManagePage .swiper-container", {
      pagination: "#activityManagePage .swiper-pagination",
      effect: "coverflow",
      grabCursor: true,
      centeredSlides: true,
      slidesPerView: "auto",
      initialSlide: initialSlide,
      coverflow: {
        rotate: 50,
        stretch: 0,
        depth: 100,
        modifier: 1,
        slideShadows: false
      }
    });
  }

  var swiper = null;

  //页面切换
  function switchPage(current) {
    current
      .addClass("selected")
      .siblings("li")
      .removeClass("selected");
    current
      .parents(".scroll-view")
      .find(".page-body")
      .children()
      .hide()
      .eq(current.index())
      .show();
    if (!current.index()) {
      initMarketingTool();
      CommonUtil.hideElement("#activityManagePage .header .right a"); // 隐藏筛选项
    } else {
      CommonUtil.showElement("#activityManagePage .header .right a"); // 隐藏筛选项
    }
  }
  function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
  $(doc).on("click", "#activityManagePage .tab-wrap>li", function() {
    var $this = $(this);
    if ($this.hasClass("selected")) {
      return;
    }

    switchPage($this);
  });

  //返回首页(vue)
  $(doc).on("click", "#activityManagePage .header .left", function() {
    AppUtil.call(AppUtil.APIS.POP_WINDOW);
  });
  // switchPage($(".tab-wrap>li.selected"));
})(document, window);
